<?php

namespace App\Service\authority;
use App\Model\Menu;
use App\Model\MenuControl;
use App\Model\MenuRole;
use App\Model\Module;
use App\Model\User;
use Hyperf\DbConnection\Db;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Cache\Annotation\CachePut;
use App\Service\CommicService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use App\Model\AuthRole;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
class AuthRoleService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }


    const STATUS_ENABLE  = 1;


    public function search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $status      = $params['status'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;

        $query = AuthRole::query()->select(['id','status','name','created_at','updated_at']);

        if ($keyword) {
            $query->orWhere([['name', 'like', '%'.$keyword.'%']]);
        }
        if ($status != '') {
            $query->where(['status' => $status]);
        }
        $models = $query->orderBy('updated_at','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            $data['status_name']    =   self::$commonStatus[$item->status];
            $selectData[] =$data;
        }
        $data = $models->toArray();
        $data['data'] = $selectData;
        return $data;
    }


    /**
     * @param $roleIds
     * @param  string  $type
     * @return array
     * 获取角色集合的菜单，游戏包，渠道权限,可使用素材用户
     */
    public function roleAuths(string $roleIds, $type = 'menu_ids')
    {
        $result = [];
        if (!$roleIds) {
            return $result;
        }
        $roles = $this->allRole();
        if (!empty($roles)) {
            $roles = json_decode($roles,true);
            foreach (explode(',', $roleIds) as $roleId) {
                isset($roles[$roleId][$type]) && $result = array_merge($result, explode(',', $roles[$roleId][$type]));
            }
        }

        return array_unique($result);
    }

    public  function allRole()
    {
        $redis = $this->redisService;

        $authRole = AuthRole::query()->where(['status' => static::STATUS_ENABLE])->pluck('name', 'id')->toArray();
//        $roleData = $redis->get(AuthRole::ENABLE_ROLE_CACHE_KEY);
//        if(empty($roleData)){
//            $redis->set(AuthRole::ENABLE_ROLE_CACHE_KEY,json_encode($authRole));
//        }
        return $authRole;
    }

    public function createOrUpdate(Array $postData,AuthRole $roleInfo = null){
        $name = $postData['name'];
        $status = $postData['status'];
        $model = !empty($roleInfo)? $roleInfo : new AuthRole();
        $model->name = $name;
        $model->status = $status;
        if($model->save()){
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
        }
    }

    public function getPermission(int $authRoldId,Array $modulesKeyVal){

        $authRoleInfo = AuthRole::query()->where(['status' => static::STATUS_ENABLE,'id'=> $authRoldId])->first();
        //拥有全部权限，查询所有菜单 $is_admin=1
        if(empty($authRoleInfo)){
            return [];
        }
        $is_admin = $authRoleInfo->is_admin;
        //不是全部权限拥有者
        if($is_admin != 1){

           $menuIds = MenuRole::query()->where(['auth_roles_id' =>$authRoldId])->pluck('menu_id')->toArray();

           if(empty($menuIds)){
             return [];
           }
        }
        if($is_admin != 1){
            $model = Menu::query()->whereIn('id',$menuIds);
        }else{
            $model = Menu::query();
        }
        $menuModels = $model->where(['status' => Menu::STATUS_SHOW])->get()->toArray();
        if(!empty($menuModels)){
            $permission = array();
            foreach ($menuModels as $menu){
                $module           = $modulesKeyVal[$menu['module_id']]['name'];
                $permission[]     = $module.':'.$menu['controller'].':'.$menu['action'];
            }
            return $permission;
        }else{

            return [];
        }
    }

    public function menuRoleList(int $roleId){

        $modules = Module::query()->where(['status' => Module::STATUS_SHOW])->select(['id','name','label'])->get();
        $menuControls = MenuControl::query()->select(['id','controller','name','sort','icon'])->get();
        $controlKeyVal = array();
        foreach ($menuControls as $menuControl){
            $controlKeyVal[$menuControl->controller] = $menuControl->toarray();
        }
        $modulesKeyVal = array();
        foreach ($modules as $module){
            $modulesKeyVal[$module->id] = $module->toarray();
        }

        //获取这个角色所拥有的权限
        $rolePermission = $this->getPermission($roleId,$modulesKeyVal);

        //获取所有菜单
        $menus = Menu::query()->get()->toArray();

        foreach ($menus as $menu) {
            $module                                              = $modulesKeyVal[$menu['module_id']]['name'];
            $moduleLable                                         = $modulesKeyVal[$menu['module_id']]['label'];
            $controller                                          = $menu['controller'];
            $controllerName                                      = $controlKeyVal[$controller]['name'];
            $menu['url']                                         = $module.':'.$controller.':'.$menu['action'];
            $treeData[$module]['label']                          = $moduleLable;
            $treeData[$module]['value']                          = $modulesKeyVal[$menu['module_id']]['name'];
            $treeData[$module]['id']                             = $modulesKeyVal[$menu['module_id']]['name'];
            $treeData[$module]['children'][$controller]['label'] = $controllerName;
            $treeData[$module]['children'][$controller]['value'] = $menu['id'];
            $treeData[$module]['children'][$controller]['key']   = $modulesKeyVal[$menu['module_id']]['name'] . '-' . $menu['controller'];
            $menu['label']  = $menu['name'];
            unset($menu['created_at']);
            unset($menu['updated_at']);
            unset($menu['deleted_at']);
            unset($menu['module_id']);
            //unset($menu['label']);
            $treeData[$module]['children'][$controller]['children'][] = $menu;
        }
        foreach ($treeData as $key => &$controller) {
            if (isset($controller['children'])) {
                $controller['children'] = array_values($controller['children']);
            }
        }
        $treeData = array_values($treeData);

        $returnData = ['treeData' => $treeData,'permission' => $rolePermission];
        return $this->response(SystemCode::SYSTEM_SUCCESS, '查询成功',$returnData);
    }

    public function authorizeSave(Array $postData){

        $role_id = $postData['role_id'];
        $menu_ids = $postData['menu_ids'];

        $roleInfo = AuthRole::query()->where('id',$role_id)->first();
        if(empty($roleInfo)){
            return $this->response(SystemCode::SYSTEM_ERROR, '角色不存在');
        }
        //清空角色权限表中的所有数据
        MenuRole::query()->where('auth_roles_id',$role_id)->delete();
        if(!empty($menu_ids)){
            foreach ($menu_ids as $menu_id){
                $model = new MenuRole();
                $model->auth_roles_id = $role_id;
                $model->menu_id = $menu_id;
                $model->save();
            }
        }

        //删除这个角色的用户redis上的权限
        $tokenIds = User::query()->where(['roles_ids' => $role_id])->pluck('access_token');
        foreach ($tokenIds as $token){
            $this->redisService->del($token);
        }
        return $this->response(SystemCode::SYSTEM_SUCCESS, '权限修改成功');
    }
}